<template>
	<div id="roleConfig">
		<el-row style="margin-bottom: 20px;">
			<el-col :span="12" style="line-height:33px;">角色配置</el-col>
			<el-col :span="12" style="text-align: right">
				<el-button
					size="small"
					type="primary"
					icon="el-icon-plus"
					@click="openDialog"
					>新增</el-button
				>
			</el-col>
		</el-row>
		<Table
			:tableData="tableData"
			:tableHead="tableHead"
			:isUseSlot="false"
			:page="listQuery.page"
			:limit="listQuery.limit"
			v-loading="listLoading"
		>
			<template slot="tool" slot-scope="{ data }">
				<el-button
					style="padding:3px;"
					icon="el-icon-document"
					@click="handleEdit(data.row)"
					v-if="!data.row.disEdit"
					type="text"
					>编辑</el-button
				>
				<el-button
					style="color:red;padding:3px;"
					v-if="!data.row.disEdit"
					icon="el-icon-delete"
					@click="delet(data.row)"
					type="text"
					>删除</el-button
				>
			</template>
		</Table>
		<Pagination
			v-show="total > 0"
			:total="total"
			:page.sync="listQuery.page"
			:limit.sync="listQuery.limit"
			@pagination="getList"
		></Pagination>
		<form-tem
			:info="{ title: '角色配置', width: '700px' }"
			:formList="formList"
			@submit="submit"
			ref="formDelg"
			@onClose="onClose"
			@change="changeSource"
		>
			<div class="tree_wrap" style=" width: 60%; height: 300px;padding-left: 19px;" v-show="formList[0].list.length === 3">
				<select-tree :defaultSelect="defaultSelect" @handleEvent="treeHandle" :listData="listData"></select-tree>
			</div>
		</form-tem>
	</div>
</template>

<script>
import Table from "@/components/Table";
import formTem from "@/template/form.temp";
import { getRoleList, getRoleInfo, insertRoleInfo, updateRoleInfo, } from "@/api/RCIM/RCIM-systemConfig";
import Pagination from "@/components/Pagination"; // 分页
import VForm from "@/components/luyiming/VueEleForm/index.vue";
import selectTree from "@/components/luyiming/SelectTree/index.vue";
import { cloneDeep } from 'lodash';
import { deleteRoleInfo } from '@/api/RCIM/RCIM-delet';
export default {
	components: {
		Table,
		Pagination,
		formTem,
		VForm,
		selectTree,
	},
	data() {
		return {
			defaultSelect: [],
			listData: [],
			selectTreeNode: [],
			tableData: [

			],
			tableHead: [
				{
					prop: "roleName",
					label: "角色名称",
					width: "",
					align: "center"
				},
				{
					prop: "XMDaccount",
					label: "是否为巡检仪账号",
					width: "",
					align: "center"
				},
				{
					prop: "operate",
					label: "操作",
					width: "",
					align: "center"
				}
			],
			listLoading: false,
			total: 0,
			listQuery: {
				page: 1,
				limit: 10
			},
			dialogFormVisible: false,
			formList: [
				{
					list: [
						{
							type: "input",
							width: "50%",
							label: "角色名称",
							placeholder: "请输入",
							moduleKey: "roleName",
							showWordLimit: true,
							maxlength: '20',
							validate: function() {
								return [
									{
										required: true,
										message: "请输入角色名称",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "switch",
							label: "是否为巡检仪账号",
							placeholder: "请选择",
							required: true,
							labelWidth: "150px",
							moduleKey: "roleType",
							width: "49%",
							defaultValue: 0,
							activeValue: 1,
							inactiveValue: 0
						},
						{
							label: "权限",
							width: '100%',
							moduleKey: "template",
							inlineMessage: true,
							validate: function() {
								return [
									{
										required: true,
										message: "角色权限不能为空",
										trigger: "blur"
									},
								];
							}
						}
					],
					title: ""
				}
			],
			formDefList: [
				{
					list: [
						{
							type: "input",
							width: "50%",
							label: "角色名称",
							placeholder: "请输入",
							moduleKey: "roleName",
							showWordLimit: true,
							maxlength: '20',
							validate: function() {
								return [
									{
										required: true,
										message: "请输入角色名称",
										trigger: "change"
									}
								];
							}
						},
						{
							type: "switch",
							label: "是否为巡检仪账号",
							placeholder: "请选择",
							required: true,
							labelWidth: "150px",
							moduleKey: "roleType",
							width: "49%",
							defaultValue: 0,
							activeValue: 1,
							inactiveValue: 0
						},
						{
							label: "权限",
							width: '100%',
							moduleKey: "template",
							inlineMessage: true,
							validate: function() {
								return [
									{
										required: true,
										message: "角色权限不能为空",
										trigger: "blur"
									},
								];
							}
						}
					],
					title: ""
				}
			],
		};
	},
	created() {
		this.getList()
	},
	methods: {
		/**
		 * @desc 删除数据
		 * @param {Object} row 表格行数据
		 */
		delet(row){
			this.$confirm('确认要删除吗？')
				.then(_ => {
					deleteRoleInfo(row.id).then(res => {
						if(res.code === 200){
							this.getList()
							return this.$message({
								type: "success",
								message: "删除成功"
							})
						}
						return this.$message({
							type: "error",
							message: "删除失败"
						})
					})
				})
				.catch(_ => {});
		},
		/**
		 * @desc 表单联动函数
		 * @param {String} keys key
		 * @param {String} value 
		 */
		changeSource(keys, value) {
			// debugger
			if (keys === "roleType") {
				const newForm = cloneDeep(this.formDefList);
				if(value === 1){
					newForm[0].list.pop()
				}
				this.formList = newForm;
			}
		},
		/**
		 * @desc 点击树回调
		 * @param {Object} param 树节点数据
		 */
		treeHandle(value){
			this.selectTreeNode = value;
			this.$refs.formDelg.getFormEle()[0][0].setDefaultValue({
				template: this.selectTreeNode.length > 0 ? '1': ''
			});
		},
		setDefTree(){

		},
		/**
		 * @desc 获取表格数据
		 */
		async getList() {
			this.listLoading = true;
			const {data} = await getRoleList(this.listQuery)
			data.roleList.forEach( item => {
				if (item.roleName === '系统管理员'){
					item.disEdit = true
				}
			})
			this.listLoading = false;
			this.tableData = data.roleList
			this.total = data.total
		},
		/**
		 * @desc 编辑表格数据
		 * @param {Object} row 表格行数据
		 */
		async handleEdit(row) {
			await this.openDialog();
			this.$nextTick( () => {
				getRoleInfo({
					id: row.id
				}).then(
					res => {
						const temp = res?.data?.data?.template || '[]'
						try{
							this.defaultSelect = JSON.parse(temp)
						}catch(e){
							this.defaultSelect = []
						}
						// 调用联动函数
						this.changeSource('roleType', res.data.data.roleType)
						delete res.data.data.template
						this.$nextTick(() => {
							// 调用内部方法
							this.$refs.formDelg.getFormEle().forEach(item => {
								item[0].setDefaultValue(res.data.data);
							});
						});
					}
				)
			})


		},
		/**
		 * @desc 关闭弹窗回调
		 */
		onClose(){
			this.defaultSelect = []
			this.listData = []
			this.$refs.formDelg.getFormEle().forEach(item => {
				item[0].deleteKeys(["id"])
			});
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submit(formData) {
			console.log(formData);
			const nods = this.selectTreeNode.map(item => item.id)
			formData.template = JSON.stringify(nods)
			if(formData.id){
				return updateRoleInfo(formData).then(res => {
					if (res.code === 200) {
						this.getList()
						this.closeDialog();
						this.selectTreeNode = [];
						return this.$message({
							type: "success",
							message: "编辑成功"
						});
					}
					return this.$message({
						type: "error",
						message: "编辑失败"
					});
				})
			}
			// 调用新增
			insertRoleInfo(formData).then(res => {
				if (res.code === 200) {
					this.closeDialog();
					this.getList()
					this.selectTreeNode = [];
					return this.$message({
						type: "success",
						message: "新增成功"
					});
				}
				return this.$message({
					type: "error",
					message: "新增失败"
				});
			})
		},
		/**
		 * @desc 关闭弹窗
		 */
		closeDialog() {
			this.$refs.formDelg.closeDialog();
		},
		/**
		 * @desc 打开弹窗
		 */
		openDialog() {
			this.$refs.formDelg.openDialog();
			return new Promise( (res, rej) => {
				try{
					setTimeout(() => {
						// 赋值全局权限
						this.listData = PERMISSION_POND;
						res()
					}, 500)
				}catch(e){
					rej()
				}

			})
		}
	}
};
</script>

<style lang="scss" scoped>
#roleConfig {
	height: calc(100vh - 144px);
	overflow: hidden;
	padding: 30px 50px;
}
</style>
